package com.rd.p2p.app.banner;

import com.alibaba.fastjson.JSONArray;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.util.BitMapUtil;
import com.qdlc.p2p.biz.util.json.JSONUtil;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.code.BASE64Encoder;
import com.qdlc.p2p.dal.checkrule.IndexRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.rd.p2p.app.user.vo.BannerVO;
import com.rd.p2p.app.user.vo.VersionNumberVO;
import com.rd.p2p.app.user.vo.ZxVO;
import org.apache.struts2.convention.annotation.Action;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 51ky on 2016/8/11.
 */
public class AppBannerAction extends BaseAction implements ModelDriven {

    private Map<String,Object> data;

    @Resource
    private UserService userService;

    @Resource
    private BorrowService borrowService;

    private IndexRuleCheck indexRuleCheck = RuleCheckHelper.getValue(IndexRuleCheck.class);

    @Action("/app/member/zxing")
    public void zxing() throws Exception{
        User user =  userService.getUserById(paramLong("userId"));
        this.getZxing(user);
    }

    @Action("/app/member/sessionZxing")
    public void sessionZxing() throws Exception{
        User user =  getSessionUser() ;
        if(user==null){
            printWebResCodeAndMsgResult("-1","用户尚未登陆");
        }
        this.getZxing(user);
    }

    private void getZxing(User user) throws Exception{
        byte[] bytes = (user.getUserId()+"").getBytes("utf-8");
        BASE64Encoder encoder = new BASE64Encoder();
        String weixinUrl =  SystemConfigHelper.getValue(SystemConfigHelper.Nid.WECHAT_URL) +"/mobile/user/register.html?sessionWeixin=true&ui="+encoder.encode(bytes);
        BitMapUtil.createQRCode(weixinUrl,this.response,1000);
    }

    /**
     * 获取banner
     *
     * @throws Exception
     */
    @Action("/app/zx/list")
    public void zxList() throws Exception {
        data = new HashMap<String, Object>();
        User user =  getSessionUser() ;
        if(user == null){
            printWebResCodeAndMsgResult("-1","用户尚未登陆");
            return;
        }
        String path= request.getSession().getServletContext().getRealPath("/");
        String JsonContext = new JSONUtil().readFile(path+"/mobile/default/json/appZX.json");
        byte[] bytes = (user.getUserId()+"").getBytes("utf-8");
        BASE64Encoder encoder = new BASE64Encoder();
        String url =  SystemConfigHelper.getValue(SystemConfigHelper.Nid.WECHAT_URL) +"/mobile/user/register.html?sessionWeixin=true&ui="+encoder.encode(bytes);
        List<ZxVO> zxList = JSONArray.parseArray(JsonContext,ZxVO.class);
        ZxVO zx =  zxList.get(0);
        zx.setUrl(url);
        data.put("data",zxList.get(0));
        data.put("resCode","1");
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 微信端首页推荐标
     *
     * @return String
     * @throws Exception
     *             if has error
     */
    @Action("/app/invest/recommendTender")
    public void recommendTender() throws Exception {
        data = new HashMap<String, Object>();
        IndexRuleCheck.NewBorrowRule borrowRule = indexRuleCheck.usuallyBorrow;
        BorrowModel model = new BorrowModel();
        model.setRows(borrowRule.count);// 件数
        model.setStatus(-2);
        model.setScales(101); //标记为不显示用户信息
        model.setCategorys(borrowRule.categorys.toArray(new Integer[0]));// BorrowCategory
        model.setTypes(borrowRule.types.toArray(new Integer[0]));// 标种
        model.setStatuss(borrowRule.statuss.toArray(new Integer[0])); // 状态
        model.setRecommend(borrowRule.recommend == 1);// 1以外非推荐标
        PageDataList<BorrowModel> pageData = borrowService.getBorrowListForIndex(model);
        List<BorrowModel> list = pageData.getList();
        String path= request.getSession().getServletContext().getRealPath("/");
        String JsonContext = new JSONUtil().readFile(path+"/mobile/default/json/appBanner.json");
        List<BannerVO> bannerList = JSONArray.parseArray(JsonContext,BannerVO.class);
        if(null!=list&&list.size()>0){
            BorrowModel borrowModel = BorrowModel.instance(list.get(0));
            data.put("borrow",borrowModel);
            data.put("accountWait", BigDecimalUtil.sub(borrowModel.getAccount(), borrowModel.getAccountYes()));
            data.put("resCode","1");
            data.put("resMsg","获取首页推荐标成功");
            data.put("bannerList", bannerList);
        }
        else{
            data.put("resCode","0");
            data.put("resMsg","获取首页推荐标失败");
        }
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * 获取banner
     *
     * @throws Exception
     */
    @Action("/app/version/list")
    public void versionList() throws Exception {
        data = new HashMap<String, Object>();
        String path= request.getSession().getServletContext().getRealPath("/");
        String JsonContext = new JSONUtil().readFile(path+"/mobile/default/json/appVersionNumber.json");
        List<VersionNumberVO> versionNumberList = JSONArray.parseArray(JsonContext,VersionNumberVO.class);
        if(versionNumberList.size()>0){
            data.put("resCode","1");
            data.put("resMsg","请求列表成功");
            data.put("versionNumber",versionNumberList.get(0));
        }
        else{
            data.put("resCode","0");
            data.put("resMsg","请求列表失败");
        }
        printWebJson(getStringOfJpaObj(data));
    }

}
